<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule\ApplicationsModule;

use Albireo\Forms\AlbireoForm;
use Nette\Application\AppForm;
use Nette\Forms\Form;
use KernelModule\BasePresenter;
use Nette\VisualPaginator;
use Albireo\Application\Application;
use Nette\Forms\SubmitButton;

/**
 * Resources
 * 
 * @inherits cancelClicked() from Kernel\Acl\BasePresenter
 * @inherits createComponentPaginator() from Kernel\Acl\BasePresenter
 * @inherits addFormButtons from Kernel\Acl\BasePresenter
 * @inherits createComponentDelete() from Kernel\Acl\BasePresenter
 *
 * @author Pavel
 */
class ManagementPresenter extends BasePresenter {

    /** @var AclManagment */
    private $appManager;

    /**
     * Lazy getter for AclManagement
     * @return AclManagement
     */
    private function getAppManager() {
        if ($this->appManager === NULL) {
            $this->appManager = new AppManagement($this->getUser());
        }
        return $this->appManager;
    }

    public function beforeRender() {
        parent::beforeRender();
        $this->showMenu();
    }

    public function renderDefault() {
        $this->template->title = _("Application Management");

        $this->bringResources();
    }

    public function handleDefault() {
        $this->bringResources();
        $this->invalidateControl("list");
    }

    private function bringResources() {
        $paginator = $this->getComponent("paginator")->getPaginator();

        $usersDataSource = $this->getAppManager()->getDataSource();

        $paginator->itemCount = $usersDataSource->count();
        $usersDataSource->applyLimit($paginator->itemsPerPage, $paginator->offset);

        $apps = $usersDataSource->fetchAll();

        $this->template->apps = $apps;
    }

    public function actionAdd() {
        $this->template->title = _("Add New Application");
        $this->view = "addOrEdit";
    }

    public function actionEdit($name) {
        $this->template->title = _("Edit Application");
        $this->view = "addOrEdit";

        $app = $this->getAppManager()->getAppByName($name);
        //TODO HANDLE exception here
        if ($app == null)
            throw new \InvalidStateException();

        $default = array(
            "name" => $app->getName(),
            "url" => $app->getUrl(),
            "publisher" => $app->getPublisher(),
            "version" => $app->getVersion(),
            "description" => $app->getAltText(),
            "system" => $app->getSystem(),
            "auto" => $app->getAuto(),
        );

        $this->template->resourceName = $app->getName();

        $form = $this->getComponent('addEdit');
        $form->setDefaults($default);
    }

    protected function createComponentAddEdit($name) {
        $form = new AlbireoForm();
       
        if($this->getAction() == "edit") {
             $input = $form->addHidden('name');
        } else {
             $input = $form->addText('name', _('Name:'), 40)
                ->addRule(Form::FILLED, _("Please, enter the app name"));
        }
        $form->addText('url', _('Url:'), 255)
                ->addRule(Form::FILLED, _("Please, enter the app url"));
        $form->addText('description', _('Description:'), 255);
        $form->addText('publisher', _('Publisher:'), 50);
        $form->addText('version', _('Version:'), 12);
        $form->addCheckbox('auto', _('Auto Install:'));
        $form->addCheckbox('system', _('System app:'));

        $this->addFormButtons($form);

        return $form;
    }

    public function addOrEditSubmitted(AlbireoForm $form) {

        $values = $form->getValues();

        $app = new Application($values["name"], $values["url"]);
        $app->setAltText($values["description"]);
        $app->setPublisher($values["publisher"]);
        $app->setSystem($values["system"]);
        $app->setVersion($values["version"]);
        $app->setAuto($values["auto"]);

        if ($this->getAction() == "add") {
            if ($this->getAppManager()->addApplication($app)) {
                $this->flashMessage(_('The application has been added.'), 'ok');
            } else {
                $this->flashMessage(_("The application can't be added, maybe already exists with same name or url."), 'error');
            }
        } elseif ($this->getAction() == "edit") {
            if ($this->getAppManager()->updateApplication($app)) {
                $this->flashMessage(_('The application has been edited.'), 'ok');
            } else {
                $this->flashMessage(_("The application can't be updated."), 'error');
            }
        } else
            throw new \InvalidStateException(); //this should never happen
        $this->redirect("default");
    }

    public function actionDelete($name) {
        $deletedResource = $this->getAppManager()->getAppByName($name);
        if ($deletedResource == NULL) {
            $this->flashMessage(_("The resource doesn't exist."), "error");
            $this->redirect('default');
        }
        $this->template->title = _("Delete Application");
        $this->template->name = $deletedResource->getName();
        $this["delete"]->setDefaults(array("name" => $deletedResource->getName()));
    }

    public function deleteOnFormSubmitted(AppForm $form) {
        if ($form['delete']->isSubmittedBy()) {
            $values = $form->getValues();
            $app = $this->getAppManager()->getAppByName($values["name"]);
            if ($this->getAppManager()->deleteApp($app)) {
                $this->flashMessage(_('The resource has been deleted succesfuly.'), 'ok');
            } else
                $this->flashMessage(_("The resource has not been deleted."), "error");
        }
        $this->redirect("default");
    }

    public function createComponentPaginator() {
        $visualPaginator = new VisualPaginator();
        $visualPaginator->paginator->setItemsPerPage(10);
        return $visualPaginator;
    }

    protected function addFormButtons($form) {
        if ($this->getAction() == 'add')
            $form->addSubmit('add', _('Add'));
        elseif ($this->getAction() == 'edit') {
            $form->addHidden("id");
            $form->addSubmit('edit', _('Edit'));
        }
        else
            throw new \InvalidStateException(); //this should never happen
        $this->addCancelButton($form);
        $form->onSubmit[] = array($this, 'addOrEditSubmitted');
    }

    protected function addCancelButton($form) {
        $form->addSubmit("cancelClicked", _("Cancel"))
                        ->setValidationScope(FALSE)
                ->onClick[] = array($this, "cancelClicked");
    }
    
    public function cancelClicked(SubmitButton $button) {
        $this->redirect('default');
    }
    
    protected function createComponentDelete() {
        $form = new AlbireoForm();
        $form->addHidden("name");
        $form->addSubmit('delete', _('Delete'));
        $form->addSubmit('cancel', _('Cancel'));
        $form->onSubmit[] = array($this, 'deleteOnFormSubmitted');
        return $form;
    }

}